package com.ruoyi.drone.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Component
public class JwtUtils {

    @Value("${jwt.secret:ruoyi-drone-secret-key-2024-very-long-and-secure-key-for-jwt-token-generation}")
    private String secret;

    @Value("${jwt.expiration:604800}")
    private Long expiration; // 7天，单位：秒

    /**
     * 生成JWT token
     * 
     * @param userId 用户ID
     * @param phone 手机号
     * @return JWT token
     */
    public String generateToken(Long userId, String phone) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("phone", phone);
        return createToken(claims, phone);
    }

    /**
     * 创建token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration * 1000);

        return Jwts.builder()
                .claims(claims)
                .subject(subject)
                .issuedAt(now)
                .expiration(expiryDate)
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * 从token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("userId", Long.class);
    }

    /**
     * 从token中获取手机号
     */
    public String getPhoneFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }


    /**
     * 从token中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 从token中获取Claims
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    /**
     * 检查token是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            Date now = new Date();
            boolean expired = expiration.before(now);
            
            System.out.println("JWT工具类 - token过期时间: " + expiration);
            System.out.println("JWT工具类 - 当前时间: " + now);
            System.out.println("JWT工具类 - 是否过期: " + expired);
            
            return expired;
        } catch (Exception e) {
            System.out.println("JWT工具类 - token解析异常: " + e.getMessage());
            return true;
        }
    }

    /**
     * 验证token
     */
    public Boolean validateToken(String token, String phone) {
        try {
            String tokenPhone = getPhoneFromToken(token);
            return (tokenPhone.equals(phone) && !isTokenExpired(token));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取签名密钥
     */
    private SecretKey getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 从请求头中获取token
     */
    public String getTokenFromHeader(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
}
